import axios from "axios";
import { ElMessage } from "element-plus";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || "/api", // url基础地址
  timeout: 1000 * 60 * 5, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 可以在这里设置token等请求头信息
    // const token = localStorage.getItem('token');
    // if (token) {
    //   config.headers['Authorization'] = `Bearer ${token}`;
    // }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 检查HTTP状态码
    if (response.status === 200) {
      return response;
    } else {
      ElMessage({
        message: "HTTP请求失败: " + response.status,
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error("HTTP请求失败"));
    }
  },
  (error) => {
    console.error("请求出错", error);
    ElMessage({
      message: error.message || "请求出错",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
